package lgkj.meicqt20.ui;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import lgkj.meicqt20.MainActivity;
import lgkj.meicqt20.R;
import lgkj.meicqt20.bean.AdverBean;
import lgkj.meicqt20.bean.AdvertlistBean;
import lgkj.meicqt20.service.TimerService;
import lgkj.meicqt20.utils.AllKindsOfConstant;
import lgkj.meicqt20.utils.DbController;
import lgkj.meicqt20.utils.HttpUtils;
import lgkj.meicqt20.utils.SharedPreferencesUtils;
import lgkj.meicqt20.utils.VideoDownLoadUtil;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/12/26 0026.
 */

public class StartActivity extends Base1Activity {


    @BindView(R.id.animationIV)
    ImageView animationIV;
    @BindView(R.id.tv_widget)
    TextView tvWidget;
    @BindView(R.id.widget_ProgressBar)
    ProgressBar widgetProgressBar;
    private AnimationDrawable animationDrawable;
    private boolean isNewVer = true;
    private AdvertlistBean advertlistBean;
    private int adverPosition = 0;
    private List<String> fileloadUrl, loadVideoUrl;
    private DbController dbController;

    @Override
    public int setContentView() {
        return R.layout.activity_start_page;
    }


    @Override
    public void init() {
        animationDrawable = (AnimationDrawable) animationIV.getDrawable();
        animationDrawable.setOneShot(false);
        animationDrawable.start();
        fileloadUrl = VideoDownLoadUtil.filePaths();
        loadVideoUrl = new ArrayList<>();
        dbController = new DbController(StartActivity.this);
        statLocation();
        startService(new Intent(this, TimerService.class));
//        dbController.delete();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    @Override
    public void initData() {
        sharedPreferencesUtils = new SharedPreferencesUtils(StartActivity.this);
        Map<String, String> params = new HashMap<>();
        params.put("zeta", HttpUtils.ver);
        HttpUtils.getHttp(params, AllKindsOfConstant.GET_VERSION_PATH, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                if (jsonObject.optInt("statue") != 0) {
                    isNewVer = false;
                    String url = jsonObject.optString("data");
                    if (url != null) {
                        downLoadNewVersionAppAndOpen(url);
                    }
                }
            }

            @Override
            public void errorHttp(String msg) {

            }
        });
        if (isNewVer)
            checkVideos();
//        startMain();

    }

    //下载新的app并打开
    private void downLoadNewVersionAppAndOpen(String apk_url) {
        dbController.delete();
        HttpUtils.getFile(apk_url, new FileCallBack(AllKindsOfConstant.NEW_VERSION_PATH, "meidiancqt_" + HttpUtils.ver + ".apk") {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "下载失败： " + e.toString());
                checkVideos();
            }

            @Override
            public void onResponse(File response, int id) {
                try {
                    Log.d(TAG, "下载完成:" + response.getPath());
                    tvWidget.setText("正在安装最新版本，请稍后");
                    String filePath = AllKindsOfConstant.NEW_VERSION_PATH + "meidiancqt_" + HttpUtils.ver + ".apk";
                    VideoDownLoadUtil.openFile(StartActivity.this, filePath);
                } catch (Exception e) {
                    tvWidget.setText("安装失败");
                    Log.e(TAG, "安装失败~");
                }
            }

            @Override
            public void inProgress(float progress, long total, int id) {
                super.inProgress(progress, total, id);
                Log.i(TAG, "下载的进度:  " + progress * 100 + "% " + "       total:    " + total);
                widgetProgressBar.setProgress((int) (progress * 100));
                tvWidget.setText("正在下载最新版本");
            }
        });
    }

    /**
     * 获取视频
     */
    private void checkVideos() {
        Map<String, String> params = new HashMap<>();
        params.put("area", "1");
        HttpUtils.getHttp(params, AllKindsOfConstant.PATH_ADVERTISEMENT, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                Gson mGson = new Gson();
                if (jsonObject.optInt("status") == 1) {
                    advertlistBean = mGson.fromJson(String.valueOf(jsonObject), AdvertlistBean.class);
                    Log.i(TAG, "advertlistBean: " + advertlistBean.getData().size());
//                    sharedPreferencesUtils.setBean("advertlistBean", advertlistBean);
//                    advertlistBean = new AdvertlistBean();
//                    advertlistBean = (AdvertlistBean) sharedPreferencesUtils.getBean("advertlistBean");
//                    Log.i(TAG, "advertlistBean: " + advertlistBean.getData().size());
                    isDownVideo();
                } else {
                    startMain();
                }
            }

            @Override
            public void errorHttp(String msg) {
                startMain();
            }
        });
    }


    /**
     * 判断是否下载视频
     */
    private void isDownVideo() {
        if (adverPosition >= advertlistBean.getData().size()) {
            startMain();
            return;
        }
        AdverBean adverBeanDao = advertlistBean.getData().get(adverPosition);
        adverBeanDao.setId(Long.valueOf(adverPosition + 1));
        Long id = dbController.insert(adverBeanDao);
        Log.i(TAG, "dbController: " + id + ",position:" + adverPosition);
        String ad_name = advertlistBean.getData().get(adverPosition).getAd_file();
        loadVideoUrl.add(VideoDownLoadUtil.getVideoFullName(ad_name));
        sharedPreferencesUtils.setDataList("videoList", loadVideoUrl);
        boolean contains = VideoDownLoadUtil.isDown(VideoDownLoadUtil.getVideoFullName(ad_name), advertlistBean.getData().get(adverPosition).getAd_file_size());
        Log.d(TAG, "第" + adverPosition + "个视频" + ((contains) ? "需要" : "不需要") + "下载!             名称:" + ad_name);
        if (contains) {
            downVideo(ad_name);
        } else {
            tvWidget.setText("不需要更新");
            float percet = (float) adverPosition / 48 * 100;
            widgetProgressBar.setProgress((int) percet);
            adverPosition++;
            isDownVideo();
        }
    }

    /**
     * 下载电影
     */
    private void downVideo(String ad_name) {
        if (adverPosition >= advertlistBean.getData().size()) {
            return;
        }
        if (ad_name == null && ad_name.length() > 0) {
            return;
        }
        Log.d(TAG, ad_name);
        HttpUtils.getFile(ad_name, new FileCallBack(VideoDownLoadUtil.mRootPath, VideoDownLoadUtil.getVideoFullName(ad_name)) {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.d(TAG, "下载失败：response:" + e.getMessage() + ",id" + id + ",mCurDownPos:" + adverPosition);
                adverPosition++;
                isDownVideo();
            }

            @Override
            public void onResponse(File response, int id) {
                Log.e(TAG, "下载完成：response:" + response.getName() + ",id" + id + ",mCurDownPos:" + adverPosition);
                adverPosition++;
                isDownVideo();
            }

            @Override
            public void inProgress(float progress, long total, int id) {
                super.inProgress(progress, total, id);
                widgetProgressBar.setProgress((int) (progress * 100));
                tvWidget.setText("共" + advertlistBean.getData().size() + "个文件，正在下载第" + (adverPosition + 1) + "个文件");
            }
        });


    }


    private void startMain() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        VideoDownLoadUtil.getUncontain(fileloadUrl, loadVideoUrl);
        finish();
    }
}
